<?php

namespace backend\services\active;

use backend\extensions\ApiBaseService;
use backend\models\active\ActivePromotion;
use backend\models\active\ActivePromotionGoods;

/**
 * Desc 促销活动管理服务类
 * @author WMX
 */
class ActivePromotionService extends ApiBaseService
{

    /**
     * 列表
     * @param array $params 参数 
     * **/
    public static function getList($params)
    {
        //检索条件
        $condition = ['AND'];
        if ($params['name']) {
            $condition[] = ['like', 'name', $params['name'] ?? ''];
        }
        $list = ActivePromotion::getDataAll($condition, $params['page'], $params['page_size']);
        foreach ($list['list'] as &$value) {
            $value['type_name'] = ActivePromotion::$type[$value['type']] ?? '';
            $value['state_name'] = ActivePromotion::$state[$value['state']] ?? '';
            $value['start_time'] = $value['start_time'] ? date('Y-m-d H:i:s', $value['start_time']) : '';
            $value['end_time'] = $value['end_time'] ? date('Y-m-d H:i:s', $value['end_time']) : '';
        }
        return $list;
    }

    /**
     * 新增
     * @param array $params 参数 
     * * */
    public static function create($params)
    {
        $time = date('Y-m-d H:i:s');
        $params['create_time'] = $time;
        $params['update_time'] = $time;

        $params['start_time'] = strtotime($params['time_range'][0]);
        $params['end_time'] = strtotime($params['time_range'][1]);
        unset($params['time_range']);

        if (in_array($params['type'], [ActivePromotion::ZHEKOU, ActivePromotion::MANJIANZHE])) {
            foreach ($params['rules'] as $rule) {
                $youhui = round($rule['youhui'] ?? 0, 2);
                if ($youhui < 1 || $youhui >= 10) {
                    return self::jsonError('折扣不能小于1且必须小于10');
                }
            }
        }

        $params['rules'] = json_encode($params['rules']);
   
        $include_barcode_arr =  !empty($params['include_barcode']) ? array_unique(explode(',', $params['include_barcode'])) : [];
        $exclude_barcode_arr =  !empty($params['exclude_barcode']) ? array_unique(explode(',', $params['exclude_barcode'])) : [];

        unset($params['include_barcode']);
        unset($params['exclude_barcode']);

        $transaction = \Yii::$app->db->beginTransaction();
        try {
            $act_id = ActivePromotion::create($params);

            $act_goods = [];
            foreach($include_barcode_arr as $val) {
                $act_goods[] = [
                    'gid' =>$val,
                    'type' => 1,
                    'activity' => $act_id,
                    'start_time' => $params['start_time'],
                    'end_time' =>  $params['end_time'],
                    'state' => $params['state'],
                    'create_time' => $params['create_time'],
                    'update_time' => $params['update_time']
                ];
            }

            foreach($exclude_barcode_arr as $val) {
                $act_goods[] = [
                    'gid' =>$val,
                    'type' => 2,
                    'activity' => $act_id,
                    'start_time' => $params['start_time'],
                    'end_time' =>  $params['end_time'],
                    'state' => $params['state'],
                    'create_time' => $params['create_time'],
                    'update_time' => $params['update_time']
                ];
            }

            \Yii::$app->db->createCommand()->batchInsert(ActivePromotionGoods::tableName(), array_keys($act_goods[0]), $act_goods)->execute();


            $transaction->commit();
            return self::jsonSuccess();
        } catch (\Exception $e) {
            $transaction->rollBack();
            return self::jsonError($e->getMessage());
        }
    }

    /**
     * 新增
     * @param array $params 参数 
     * * */
    public static function update($params)
    {
        $id = $params['id'];

        unset($params['id']);
    
        $params['start_time'] = strtotime($params['time_range'][0]);
        $params['end_time'] = strtotime($params['time_range'][1]);
        unset($params['time_range']);

        if (in_array($params['type'], [ActivePromotion::ZHEKOU, ActivePromotion::MANJIANZHE])) {
            foreach ($params['rules'] as $rule) {
                $youhui = round($rule['youhui'] ?? 0, 2);
                if ($youhui < 1 || $youhui >= 10) {
                    return self::jsonError('折扣不能小于1且必须小于10');
                }
            }
        }

        $params['update_time'] = date('Y-m-d H:i:s');
        $params['rules'] = json_encode($params['rules']);

        $include_barcode = $params['include_barcode'];
        $exclude_barcode = $params['exclude_barcode'];
        $include_barcode_arr = array_unique(explode(',', $include_barcode));
        $exclude_barcode_arr = array_unique(explode(',', $exclude_barcode));

        unset($params['include_barcode']);
        unset($params['exclude_barcode']);

        $transaction = \Yii::$app->db->beginTransaction();
        try {
            ActivePromotion::updateData($params, ['id'=> $id]);
            ActivePromotionGoods::deleteAll(['activity' => $id]);

            $act_goods = [];
            foreach($include_barcode_arr as $val) {
                $act_goods[] = [
                    'gid' =>$val,
                    'type' => 1,
                    'activity' => $id,
                    'start_time' => $params['start_time'],
                    'end_time' =>  $params['end_time'],
                    'state' => $params['state'],
                    'create_time' => $params['update_time'],
                    'update_time' => $params['update_time']
                ];
            }

            foreach($exclude_barcode_arr as $val) {
                $act_goods[] = [
                    'gid' =>$val,
                    'type' => 2,
                    'activity' => $id,
                    'start_time' => $params['start_time'],
                    'end_time' =>  $params['end_time'],
                    'state' => $params['state'],
                    'create_time' => $params['update_time'],
                    'update_time' => $params['update_time']
                ];
            }

            \Yii::$app->db->createCommand()->batchInsert(ActivePromotionGoods::tableName(), array_keys($act_goods[0]), $act_goods)->execute();

            $transaction->commit();
            return self::jsonSuccess();
        } catch (\Exception $e) {
            $transaction->rollBack();
            return self::jsonError($e->getMessage());
        }
    }

    /**
     * 删除
     * @param array $params 参数 
     * * */
    public static function delete($params)
    {
        $id = $params['id'];
        $transaction = \Yii::$app->db->beginTransaction();
        try {
            // 保存专题
            ActivePromotion::del(['id'=>$id]);
            ActivePromotionGoods::deleteAll(['activity' => $id]);

            $transaction->commit();
            return self::jsonSuccess();
        } catch (\Exception $e) {
            $transaction->rollBack();
            return self::jsonError($e->getMessage());
        }
    }

    /**
     * 详情
     * @param array $params 参数 
     * **/
    public static function detail($params)
    {
        $condition = ['id' => $params['id']];
        $data = ActivePromotion::getDataOne($condition, '', []);
        $data['rules'] = json_decode($data['rules']);

        $include_ids= ActivePromotionGoods::getIndexAll('gid',['activity'=> $params['id'],'type'=> 1], 'gid');
        $include_ids = array_keys($include_ids);
        $data['include_barcode']  = implode(',', $include_ids);

        $exclude_ids= ActivePromotionGoods::getIndexAll('gid',['activity'=> $params['id'],'type'=> 2], 'gid');
        $exclude_ids = array_keys($exclude_ids);
        $data['exclude_barcode']  = implode(',', $exclude_ids);

        $data['time_range'] = [date('Y-m-d H:i:s',$data['start_time']),date('Y-m-d H:i:s',$data['end_time']) ];

        return self::jsonSuccess($data);
    }
}
